<script setup>

import {ref, onMounted, watch, computed} from 'vue';
import axios from "axios";
import {snackbar} from './store'
import moment from "moment"

// 查询
const pageSize = ref(10);
const pageNo = ref(1)
const headers = [
    {title: '序号', key: 'num', sortable: false},
    {title: '巡检员', key: 'checkUserName', sortable: false},
    {title: '巡检地点', key: 'checkPlaceName', sortable: false},
    {title: '记录时间', key: 'recordTime', sortable: false},
    {title: '详情描述', key: 'checkContent', sortable: false},
    {title: '异常等级', key: 'abnormalLev', sortable: false},
    {title: '备注', key: 'remark', sortable: false},
    {title: '特殊备注', key: 'remarkSpecial', sortable: false},
    {title: '事件状态', key: 'eventType', sortable: false},
    {title: '处理方法', key: 'handleMethod', sortable: false},
    {title: '处理结果', key: 'handleResult', sortable: false},
    {title: '处理人', key: 'handlePerson', sortable: false},
    {title: '操作', key: 'actions', sortable: false}
];
const items = ref([]);
const loading = ref(true);
const totalItems = ref(0);

const isShowDialogStartDate = ref(false);
const isShowDialogEndDate = ref(false);
const startDate = ref(null);
const endDate = ref(null);
const dateSearch = ref(new Date());
const dateSearchEnd = ref(new Date());
const search = ref('');
const name = ref(null);
const userList = ref([]);
const checkPlaceList = ref([]);
const imgBaseUrl = ref("http://172.168.180.4:800/");
const placeName = ref(null);
const password = ref(null);
const active = ref(0);
watch(name, () => {
    search.value = name.value
})
watch(placeName, () => {
    search.value = placeName.value
})
watch(startDate, () => {
    search.value = startDate.value
})
watch(endDate, () => {
    search.value = endDate.value
})

function loadItems({page, itemsPerPage}) {
    loading.value = true;
    pageNo.value = page
    pageSize.value = itemsPerPage
    axios.post('/checkRecordAbnormal/select', {
        pageNo: page,
        pageSize: itemsPerPage,
        checkContent: name.value,
        placeId: placeName.value,
        startDate: startDate.value,
        endDate: endDate.value
    }).then(({data}) => {
        items.value = data.data.records;
        totalItems.value = data.data.total;
        loading.value = false;
    })
}

onMounted(() => {
    loadItems({page: 1, itemsPerPage: pageSize.value});
    axios.post('/user/selectPage', {
        pageNo: 1,
        pageSize: 100,
        delFlag: '0'
    }).then(({data}) => {
        userList.value = data.data.records;
    })
    axios.post('/checkPlace/getAll', {}).then(({data}) => {
        checkPlaceList.value = data.data;
    })
});

// 增改
const isShowDialog = ref(false)
const dialogEnum = {
    update: '编辑',
    create: '新增'
}
const dialogType = ref(null)
const isShowDeleteDialog = ref(false)
const editedItem = ref({
    userId: "",
    recordTime: "",
    placeId: "",
    checkContent: "",
    itemsId: "",
    imgsId: ""
});

function resetEditedItem() {
    editedItem.value = {
        userId: "",
        recordTime: "",
        placeId: "",
        checkContent: "",
        abnormalLev: "",
        remark: "",
        remarkSpecial: "",
        eventType: "",
        handleMethod: "",
        handleResult: "",
        handlePerson: "",
        itemsId: "",
        imgsId: ""
    }
}

function clickNew() {
    dialogType.value = dialogEnum.create
    resetEditedItem()
    isShowDialog.value = true
}

function close() {
    isShowDialog.value = false
    resetEditedItem()
    dialogType.value = null
}

function clickEdit(item) {
    editedItem.value = Object.assign({}, item)
    editedItem.value.abnormalLev += ''
    editedItem.value.eventType += ''
    editedItem.value.itemsId = JSON.parse(editedItem.value.itemsId)
    editedItem.value.itemsFireId = JSON.parse(editedItem.value.itemsFireId)
    editedItem.value.imgsId = JSON.parse(editedItem.value.imgsId)
    editedItem.value.itemsAbnormalId = JSON.parse(editedItem.value.itemsAbnormalId)
    editedItem.value.imgsAbnormalId = JSON.parse(editedItem.value.imgsAbnormalId)
    editedItem.value.handleFlowOrder = [{name: "", time: ""}, {name: "", time: ""}]
    editedItem.value.handleFlow = JSON.parse(item.handleFlow)
    getFlow(editedItem.value.handleFlow, JSON.parse(item.handleFlowOrder))
    isShowDialog.value = true
    dialogType.value = dialogEnum.update
}

function getFlow(val, row) {
  row = row ? row : []
  editedItem.value.handleFlow[0] = val[0] ? val[0] : {name:"", time: ""}
  editedItem.value.handleFlow[1] = val[1] ? val[1] : {name:"", time: ""}
  editedItem.value.handleFlowOrder[0] = row[0] ? row[0] : {name:"", time: ""}
  editedItem.value.handleFlowOrder[1] = row[1] ? row[1] : {name:"", time: ""}
  if(!!editedItem.value.handleFlow[1].name) { active.value = 1 }
  if(!!editedItem.value.handleFlowOrder[0].name) { active.value = 2 }
  if(!!editedItem.value.handleFlowOrder[1].name) { active.value = 3 }
  editedItem.value.handleFlow[2] = val[2] ? val[2] : {name:"", time: ""}
  if(!!editedItem.value.handleFlow[2].name) { active.value = 4 }
}

function save() {
    if (dialogType.value === dialogEnum.update) {
        axios({
            method: 'POST',
            url: '/checkRecordAbnormal/update',
            data: editedItem.value
        }).then(() => {
            snackbar.info('编辑成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        })
    } else if (dialogType.value === dialogEnum.create) {
        axios({
            method: 'POST',
            url: '/checkRecordAbnormal/save',
            data: editedItem.value
        }).then((res) => {
            console.log(res.data)
            snackbar.info('创建成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        })
    }
}

// 删
const beDeleteItem = ref({})

function clickDelete(item) {
    password.value = null
    isShowDeleteDialog.value = true
    beDeleteItem.value = item
}

function clickDeleteConfirm() {
    if(password.value == '123456') {
        let obj = {
            id: beDeleteItem.value.id
        }
        axios.post('/checkRecordAbnormal/delete', obj).then(() => {
            snackbar.info("删除成功")
            loadItems({page: 1, itemsPerPage: pageSize.value})
            clickCloseDelete()
        })
    } else {
        snackbar.info("密码错误")
    }
}

function clickCloseDelete() {
    isShowDeleteDialog.value = false
    beDeleteItem.value = null
}

function changeDate() {
    startDate.value = moment(dateSearch.value).format('YYYY-MM-DD')
    isShowDialogStartDate.value = false
}

function changeDateEnd() {
    endDate.value = moment(dateSearchEnd.value).format('YYYY-MM-DD')
    isShowDialogEndDate.value = false
}

function downloadFile() {
    let obj = {
        startDate: startDate.value,
        endDate: endDate.value,
        placeId: placeName.value
    }
    axios({
        method: "POST",
        url: "/checkRecordAbnormal/export",
        responseType: 'blob',
        data: obj
    }).then(res => {}, err => {
        let blob = new Blob([err.data], {type: "application/vnd.ms-excel"});
        let fileName = `${moment(new Date()).format("YYYY-MM-DD")}巡检异常记录.xls`
        if ("download" in document.createElement("a")) {
            // 支持a标签download的浏览器
            const link = document.createElement("a"); // 创建a标签
            link.download = fileName; // a标签添加属性
            link.style.display = "none";
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click(); // 执行下载
            URL.revokeObjectURL(link.href); // 释放url
            document.body.removeChild(link); // 释放标签
        } else {
            // 其他浏览器
            navigator.msSaveBlob(blob, fileName);
        }
    })
}

</script>

<template>
    <v-toolbar density="compact">
        <v-toolbar-title>巡检异常记录管理</v-toolbar-title>
        <v-autocomplete v-model="placeName" :items="checkPlaceList" item-value="id" item-title="placeName" label="巡检地点" :clearable="true" hide-details placeholder="巡检地点"></v-autocomplete>
        <v-text-field v-model="name" :clearable="true" hide-details placeholder="查询详情描述"></v-text-field>
        <v-text-field v-model="startDate" readonly :clearable="true" hide-details placeholder="开始时间" label="开始时间" @click="isShowDialogStartDate = true"></v-text-field>
        <v-dialog v-model="isShowDialogStartDate" max-width="500px">
            <v-date-picker v-model="dateSearch" @update:model-value="changeDate"></v-date-picker>
        </v-dialog>
        <v-text-field v-model="endDate" readonly :clearable="true" hide-details placeholder="结束时间" label="结束时间" @click="isShowDialogEndDate = true"></v-text-field>
        <v-dialog v-model="isShowDialogEndDate" max-width="500px">
            <v-date-picker v-model="dateSearchEnd" @update:model-value="changeDateEnd"></v-date-picker>
        </v-dialog>
        <v-btn icon="mdi-upload" @click="downloadFile"></v-btn>
        <v-dialog v-model="isShowDialog" max-width="800px">
            <!-- <template v-slot:activator="{ props }">
                <v-btn icon="mdi-plus" v-on:click="clickNew" v-bind="props"></v-btn>
            </template> -->
            <v-card>
                <v-card-title>{{ dialogType }}</v-card-title>
                <v-card-text>
                    <v-select readonly v-model="editedItem.userId" label="巡检员" required :items="userList" item-value="id" item-title="nickname"></v-select>
                    <v-text-field readonly v-model="editedItem.recordTime" label="记录时间"></v-text-field>
                    <v-select readonly v-model="editedItem.placeId" label="巡检地点" required :items="checkPlaceList" item-value="id" item-title="placeName"></v-select>
                    <v-text-field readonly v-model="editedItem.checkContent" label="详情描述"></v-text-field>
                    <v-select readonly v-model="editedItem.abnormalLev" label="异常等级" required :items="[{value:'0',title:'绿色警报'},{value:'1',title:'黄色警报'},{value:'2',title:'橙色警报'},{value:'3',title:'红色警报'}]"></v-select>
                    <v-text-field readonly v-model="editedItem.remark" label="备注"></v-text-field>
                    <v-text-field readonly v-model="editedItem.remarkSpecial" label="特殊备注"></v-text-field>
                    <v-select readonly v-model="editedItem.eventType" label="事件状态" required :items="[{value:'0',title:'未处理'},{value:'1',title:'处理中'},{value:'2',title:'已办结'}]"></v-select>
                    <v-text-field readonly v-model="editedItem.handleMethod" label="处理方法"></v-text-field>
                    <v-text-field readonly v-model="editedItem.handleResult" label="处理结果"></v-text-field>
                    <v-text-field readonly v-model="editedItem.handlePerson" label="处理人"></v-text-field>
                    <h2>网格化巡检项：</h2>
                    <div v-for="(item, index) in editedItem.itemsId" :key="item.id">
                        <span>{{ index + 1 }}. {{ item.itemName }}</span>
                        :
                        <el-button type="primary" plain size="mini">{{ item.itemIf ? '正常' : '异常' }}</el-button> 
                        <br>       
                    </div>
                    <h2>消防日检：</h2>
                    <div v-for="(item, index) in editedItem.itemsFireId" :key="item.id">
                        <span>{{ index + 1 }}. {{ item.itemName }}</span>
                        :
                        <el-button type="primary" plain size="mini">{{ item.itemIf ? '正常' : '异常' }}</el-button> 
                        <br>       
                    </div>
                    <h2>巡检图片：</h2>
                    <el-image v-for="item in editedItem.imgsId" :src="imgBaseUrl + item" :preview-src-list="[imgBaseUrl + item]" style="height: 200px;" alt=""></el-image>
                    <h2>巡检异常项：</h2>
                    <div v-for="(item, index) in editedItem.itemsAbnormalId" :key="item.id">
                        {{ index + 1 }}.
                        <span>{{ item.itemName }}</span>
                        <el-button v-if="item.abnormalLev == 0" size="mini" type="warning" plain>绿色警报</el-button>
                        <el-button v-if="item.abnormalLev == 1" size="mini" type="warning">黄色警报</el-button>
                        <el-button v-if="item.abnormalLev == 2" size="mini" type="danger">橙色警报</el-button>     
                        <el-button v-if="item.abnormalLev == 3" size="mini" type="danger">红色警报</el-button>     
                    </div>
                    <h2>异常图片：</h2>
                    <el-image v-for="item in editedItem.imgsAbnormalId" :src="imgBaseUrl + item" :preview-src-list="[imgBaseUrl + item]" style="height: 200px;" alt=""></el-image>
                    <h2>巡检流程：</h2>
                    <el-steps style="max-width: 600px" :active="active" finish-status="success">
                        <el-step :title="'安全员:' + editedItem.handleFlow[0].name " :description="'发现异常：' + editedItem.handleFlow[0].time"/>

                        <el-step :title="'处理员:' + editedItem.handleFlowOrder[0].name " :description="'处理异常：' + editedItem.handleFlowOrder[0].time"/>

                        <el-step v-if="editedItem.handleFlowOrder[0].name" :title="'维修人员:' + editedItem.handleFlow[1].name " :description="'派单时间：' + editedItem.handleFlow[1].time"/>
                        <el-step v-else :title="'处理员:' + editedItem.handleFlow[1].name" :description="'派单时间：' + editedItem.handleFlow[1].time"/>

                        <el-step v-if="editedItem.handleFlowOrder[1].name && !editedItem.handleFlowOrder[0].name" :title="'维修人员:' + editedItem.handleFlowOrder[1].name " :description="'维修完成' + editedItem.handleFlowOrder[1].time"/>
                        <el-step v-if="editedItem.handleFlowOrder[1].name && editedItem.handleFlowOrder[0].name" :title="'确认人员:' + editedItem.handleFlowOrder[1].name " :description="'维修完成' + editedItem.handleFlowOrder[1].time"/>

                        <el-step v-if="!editedItem.handleFlowOrder[0].name" :title="'安全员:' + editedItem.handleFlow[2].name " :description="'事件结束' + editedItem.handleFlow[2].time"/>
                        <el-step v-if="editedItem.handleFlowOrder[0].name" :title="'销号人员:' + editedItem.handleFlow[2].name " :description="'事件结束' + editedItem.handleFlow[2].time"/>
                    </el-steps>
                </v-card-text>
                <v-card-actions>
                    <v-btn color="primary" variant="text" @click="close">关闭</v-btn>
                    <!-- <v-btn color="primary" variant="text" @click="save">确定</v-btn> -->
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-dialog v-model="isShowDeleteDialog" max-width="500px">
            <v-card>
                <v-card-title class="text-h5">确定删除?请输入密码</v-card-title>
                <v-text-field v-model="password" label="删除密码"></v-text-field>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue-darken-1" variant="text" @click="clickCloseDelete">取消</v-btn>
                    <v-btn color="blue-darken-1" variant="text" @click="clickDeleteConfirm">确定</v-btn>
                    <v-spacer></v-spacer>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-toolbar>
  <!--  分页文本待更换   items-per-page-text="每页数量"-->
    <v-data-table-server :search="search" :items-per-page="pageSize" :headers="headers" :items-length="totalItems"
    :items="items"
    :loading="loading"
    class="elevation-1"
    items-per-page-text="每页数量"
    @update:options="loadItems">
        <template v-slot:item.num="{ index }">
            <span>{{ index + 1 }}</span>
        </template>
        <template v-slot:item.abnormalLev="{ item }">
            <span style="color: green;" v-if="item.raw.abnormalLev == 0">绿色警报</span>
            <span style="color: yellow;" v-if="item.raw.abnormalLev == 1">黄色警报</span>
            <span style="color: orangered;" v-if="item.raw.abnormalLev == 2">橙色警报</span>
            <span style="color: darkred;" v-if="item.raw.abnormalLev == 3">红色警报</span>
        </template>
        <template v-slot:item.eventType="{ item }">
            <span v-if="item.raw.eventType == 0">未处理</span>
            <span v-if="item.raw.eventType == 1">处理中</span>
            <span v-if="item.raw.eventType == 2">已办结</span>
        </template>
        <template v-slot:item.actions="{ item }">
            <v-btn icon="mdi-file-find" variant="text" @click="clickEdit(item.raw)"></v-btn>
            <v-btn icon="mdi-delete" variant="text" @click="clickDelete(item.raw)"></v-btn>
        </template>
    </v-data-table-server>
</template>

<style scoped lang="less">

</style>
